import React, { Component } from 'react'
import { Link, withRouter } from 'react-router-dom'
import { Menu, Icon } from 'antd'

import configMenu from '../../config/configMenu'
import './index.less'
import logo from './images/logo.png'

const { SubMenu } = Menu
/**
 * 左侧导航
 */
class LeftNav extends Component {
    // 这个方法在第一次render渲染的时候执行一次（同步的准备）
    componentWillMount(){
        this.nodeList = this.getNode(configMenu)
    }
    getNode = (menus) => {
        const { pathname } = this.props.location
        return menus.map(val => {
            const { children } = val
            if (!children || children.length === 0) {
                return (
                    <Menu.Item key={val.key}>
                        <Link to={val.key}>
                            {
                                val.icon && <Icon type={val.icon} />
                            }
                            <span>{val.title}</span>
                        </Link>
                    </Menu.Item>
                )
            } else {
                const ckey = val.children.find(item => item.key === pathname)
                if (ckey) this.openKey = val.key
                return (
                    <SubMenu
                        key={val.key}
                        title={
                            <span>
                                <Icon type={val.icon} />
                                <span>{val.title}</span>
                            </span>
                        }
                    >
                        {this.getNode(val.children)}
                    </SubMenu>
                )
            }
        })
    }
    render () {
        const { pathname } = this.props.location
        const openKey = this.openKey
        const { collapsed } = this.props
        return (
            <div className='left-nav' >
                <Link to='/home' className={['left-nav-header',collapsed?'mini_menu':''].join(' ')}>
                    <img src={logo} alt="公共资源平台" style={{marginRight: collapsed?'0':''}}/>
                    {
                        !this.props.collapsed?<h1>公共资源平台</h1>:''
                    }
                </Link>
                <Menu
                    selectedKeys={[pathname]}
                    defaultOpenKeys={[openKey]}
                    mode="inline"
                >
                    {this.nodeList}
                </Menu>
            </div>
        );
    }
}

/**
 * withRouter:高阶组件
 * 包装非路由组件成为一个路由组件
 * 新的路由组件像非路由组件传递三个参数，history/location/match
 */
export default withRouter(LeftNav);